import { toast } from './uni-api.js'

/**
 * 校验字符串不为空
 * @param {Object} str
 * @param {Object} fieldStr
 */
function isNotEmpty(value, fieldStr) {
	if ((typeof(value) == 'string' && value.trim().length == 0)) {
		toast(fieldStr + '不能为空');
		return false;
	}
	return true;
}

// 校验不能为数字 0
function isNotZero(value, fieldStr){
	if (!isNaN(Number(value)) && Number(value) === 0) {
		toast(fieldStr + '不能为0');
		return false;
	}
	return true;
}


/**
 * 校验手机号
 */
function isPhone(phone, fieldStr) {
	const reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
	if (!reg.test(phone)) {
		toast(fieldStr + '格式不正确');
		return false;
	}
	return true;
}


/**
 * 校验身份证号
 * @param {Object} cardId
 */
function isIdCard(cardId, fieldStr) {
	
	// 日期转字符串 返回日期格式 20080808
	function dateToString(date) {
		if (date instanceof Date) {
			var year = date.getFullYear();
			var month = date.getMonth() + 1;
			month = month < 10 ? '0' + month : month;
			var day = date.getDate();
			day = day < 10 ? '0' + day : day;
			return year + month + day;
		}
		return '';
	}
	
	// 身份证正则表达式(18位)
	var isIdCard2 = /^[1-9]\d{5}(19\d{2}|[2-9]\d{3})((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])(\d{4}|\d{3}X)$/i;
	var stard = "10X98765432"; //最后一位身份证的号码
	var first = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; //1-17系数
	var sum = 0;
	if (!isIdCard2.test(cardId)) {
		toast(fieldStr + '格式不正确');
		return false;
	}
	var year = cardId.substr(6, 4);
	var month = cardId.substr(10, 2);
	var day = cardId.substr(12, 2);
	var birthday = cardId.substr(6, 8);
	//校验日期是否合法
	if (birthday != dateToString(new Date(year + '/' + month + '/' + day))) {
		toast(fieldStr + '格式不正确');
		return false;
	}
	for (var i = 0; i < cardId.length - 1; i++) {
		sum += cardId[i] * first[i];
	}
	var result = sum % 11;
	var last = stard[result]; //计算出来的最后一位身份证号码
	if (cardId[cardId.length - 1].toUpperCase() == last) {
		return true;
	} else {
		toast(fieldStr + '格式不正确');
		return false;
	}
}



export default {
	isPhone,
	isNotEmpty,
	isNotZero,
	isIdCard
}